package com.lyf.juc.learn.sggadvance.future;

import org.junit.Test;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * @author LYF
 * @date 2022/6/29
 */

public class CompleteFutureTests {
    /*
    Future接口
    推导
    目标点：多线程、有返回值、异步任务
    Thread → Runnable/Callable → Future、FutureTask
     Future:接口，定义有返回值、异步任务
     FutureTask<V> implements RunnableFuture<V>
     构造注入 callable实现 返回值
     FutureTask(Callable<V> callable)
     */
    @Test
    public void test0() throws Exception{
        //CompletableFuture<>
        FutureTask<Integer> futureTask = new FutureTask(()-> {
            int sum=0;
            for (int i=1;i<10;i++){
                /// 模拟计算任务
               // TimeUnit.MILLISECONDS.sleep(100);
                sum+=i;
            }
            return sum;
        });
        futureTask.run();

        System.out.println("Main exec");
        // 监工
        while (!futureTask.isDone()){
            System.out.println("wait...");
            //TimeUnit.MILLISECONDS.sleep(50);
        }
        System.out.println(futureTask.get());
    }
    /*


     */
    @Test
    public void test1(){
        // 不推荐使用
        CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
        //completableFuture.

        CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(()-> "hello");

        //Executor executor = new ThreadPoolExecutor();
        //Executors
        // ExecutorService

        //1.静态方法创建-- runAsync\supplyAsync

//        Executor executor = new ThreadPoolExecutor(2,3,1,TimeUnit.SECONDS,new LinkedBlockingQueue<>());
//        executor.execute();
        // ExecutorService extends Executor
        ExecutorService executorService = new ThreadPoolExecutor(2,3,1,TimeUnit.SECONDS,new LinkedBlockingQueue<>());

        CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName());
            return "ok";
        },executorService);

        //completableFuture2.whenComplete((s, throwable) -> System.out.println(s));
        //completableFuture1.t


    }
}
